package com.ai.web.interceptor;

/**openId效验*/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.ai.web.controller.BaseController;
import com.ai.web.service.WxUserService;
import com.tiny.persistence.domain.WxUser;

public class OpenIdInterceptor extends HandlerInterceptorAdapter {
	
	private static Logger logger = Logger.getLogger(OpenIdInterceptor.class);
	
	@Autowired
	private WxUserService wxUserService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod hm = (HandlerMethod) handler;
		Object bean = hm.getBean();
		if (bean instanceof BaseController) {
			BaseController bc = (BaseController) bean;
			bc.setRequest(request);
			bc.setResponse(response);
		}
		
		logger.info("request Uri:" + request.getRequestURI() + " queryString:" + request.getQueryString());
		
		String openId = request.getParameter("openId");
		logger.info("request Uri:" + request.getRequestURI() + " openId:"+ openId);
		WxUser wxUser = wxUserService.getByOpenId(openId);
		
		if(wxUser==null) {
			return false;
		}
		else {
			return true;
		}
	}
}
